import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getRepository, Like } from 'typeorm';
import { InjectSchedule, Schedule } from 'nest-schedule';
import { Post } from './entity/post.entity';
import { Cover } from './entity/cover.entity';
import { randomString } from '../../common/utils/index';

@Injectable()
export class PostService {
  constructor(
    @InjectSchedule() private readonly schedule: Schedule,
    @InjectRepository(Post) private readonly postRepository: Repository<Post>,
    @InjectRepository(Cover)
    private readonly coverRepository: Repository<Cover>,
  ) {}

  async createPost(params) {
    const {
      title,
      content,
      postType,
      coverSize,
      videoUrl,
      coverUrlList,
      userId
    } = params;
    console.log('帖子参数', params);
    // 动态生成帖子ID
    const postId = randomString(18);
    // 保存帖子
    const postInfo = await this.postRepository.save({
      postId,
      title,
      content,
      postType,
      coverSize,
      videoUrl,
      userId,
      updateTime: new Date().getTime().toString(),
    });
    // 保存帖子相关的封面图
    if (coverUrlList && coverUrlList.length > 0) {
      for (let item of coverUrlList) {
        this.coverRepository.save({
          id: (Math.random() * 1000000).toString().substr(0, 6),
          postId,
          coverImg: item,
        });
      }
    }
    if (postInfo) {
      return {
        msg: '创建成功',
        data: {
          postId,
        },
      };
    }
  }

  // 更新帖子
  async updatePostByPostId(postId: string, params) {
    const {
      title,
      content,
      postType,
      coverSize,
      videoUrl,
      coverUrlList,
      userId,
    } = params;
    console.log('更新帖子参数', params);
    // 更新帖子
    const result = await getRepository(Post)
      .createQueryBuilder()
      .update(Post)
      .set({
        postId,
        title,
        content,
        postType,
        coverSize,
        videoUrl,
        userId,
        updateTime: new Date().getTime().toString(),
      })
      .where('postId = :postId', { postId })
      .execute();

    // 删除帖子相关的封面图
    let coverResult = await this.coverRepository.find({
      where: {
        postId,
      },
    });
    await this.coverRepository.remove(coverResult);

    // 保存帖子相关的封面图
    if (coverUrlList && coverUrlList.length > 0) {
      for (let item of coverUrlList) {
        this.coverRepository.save({
          id: (Math.random() * 1000000).toString().substr(0, 6),
          postId,
          coverImg: item,
        });
      }
    }

    if (result) {
      return {
        msg: '更新成功',
        data: {
          postId,
        },
      };
    }
  }

  // 定时任务
  async createSchedulePost(params) {
    const scheduleTime = new Date(Number(params.scheduleTime)),
      minute = scheduleTime.getMinutes(),
      hour = scheduleTime.getHours(),
      day = scheduleTime.getDate(),
      month = scheduleTime.getMonth() + 1;
    console.log(`* ${minute} ${hour} ${day} ${month} *`);
    this.schedule.scheduleCronJob(
      `${params.scheduleTime}`,
      `* ${minute} ${hour} ${day} ${month} *`,
      () => {
        this.createPost(params);
        return true;
      },
    );
    return true;
  }

  // 查询帖子列表
  async queryPostList(
    pageIndex: number,
    pageSize: number,
    keyWord: string,
    beginTime: number,
    endTime: number,
    userId: string,
  ) {
    let postCount = 0,
      pageData = null,
      dataMapResult = 'select * from post',
      dataCountResult = 'select count(1) from post',
      limit = `limit ${pageIndex * pageSize},${pageSize}`;

    if (keyWord && beginTime) {
      // 关键字、日期
      let queryByKeywordAndTime = `${dataMapResult} where updateTime between ${beginTime} and ${endTime} and title like '%${keyWord}%' and userId = ${userId} order by updateTime desc ${limit}`;
      let queryByKeywordAndTimeCount = `${dataCountResult} where updateTime between ${beginTime} and ${endTime} and title like '%${keyWord}%' and userId = ${userId} ${limit}`;
      pageData = await this.postRepository.query(queryByKeywordAndTime);
      postCount = await this.postRepository.query(queryByKeywordAndTimeCount);
    } else if (keyWord) {
      // 关键字模糊查询
      let queryByKeyword = `${dataMapResult} where title like '%${keyWord}%' and userId = ${userId} order by updateTime desc ${limit}`;
      let queryByKeywordCount = `${dataCountResult} where title like '%${keyWord}%' and userId = ${userId} ${limit}`;
      pageData = await this.postRepository.query(queryByKeyword);
      postCount = await this.postRepository.query(queryByKeywordCount);
    } else if (beginTime) {
      // 日期查询
      let queryByTime = `${dataMapResult} where updateTime between ${beginTime} and ${endTime} and userId = ${userId} order by updateTime desc ${limit}`;
      let queryByTimeCount = `${dataCountResult} where updateTime between ${beginTime} and ${endTime} and userId = ${userId} ${limit}`;
      pageData = await this.postRepository.query(queryByTime);
      postCount = await this.postRepository.query(queryByTimeCount);
    } else {
      let queryByAny = `${dataMapResult} where userId = ${userId} order by updateTime desc ${limit}`;
      pageData = await this.postRepository.query(queryByAny);
      [, postCount] = await this.postRepository.findAndCount({
        where: {
          userId,
        },
      });
    }

    for (let item of pageData) {
      let queryImgByPostId = `select a.coverImg from cover a where postId = '${item['postId']}'`;
      let mapResult = await this.coverRepository.query(queryImgByPostId);
      item.coverImg = [];
      mapResult &&
        mapResult.forEach(element => {
          item.coverImg.push(element.coverImg);
        });
    }
    typeof postCount === 'number'
      ? ''
      : (postCount = parseInt(postCount[0]['count(1)']));

    return {
      msg: '查询成功',
      data: {
        pageData,
        total: postCount,
      },
    };
  }

  // 查询帖子详情
  async queryPostDetail(postId: string) {
    let queryPostByPostId = `select * from post where postId = '${postId}'`;
    let result = await this.postRepository.query(queryPostByPostId);
    result = result[0];
    result.coverImg = [];
    let imgResult = await this.coverRepository.find({ postId });
    imgResult &&
      imgResult.forEach(element => {
        result.coverImg.push(element.coverImg);
      });

    return {
      msg: '查询成功',
      data: result,
    };
  }

  // 删除帖子
  async deletePost(postId: string) {
    let result = await this.postRepository.findOne({ postId });
    if (result) {
      let coverResult = await this.coverRepository.find({
        where: {
          postId,
        },
      });
      await this.coverRepository.remove(coverResult);
      await this.postRepository.remove(result);
      return {
        msg: '删除成功',
      };
    } else {
      return {
        msg: '帖子不存在',
        code: 1,
      };
    }
  }
}
